
import { _decorator, Component, Node, instantiate, Prefab, resources, JsonAsset, math } from 'cc';
import { Message } from '../../script/Message';
import { ModuleBase } from '../../script/ModuleBase';
import { ActorBase } from './ActorBase';
import { MonsterBase } from './MonsterBase';
import { RoleBase } from './RoleBase';
const { ccclass, property } = _decorator;



@ccclass('Actor')
export class Actor extends ModuleBase {
    @property(JsonAsset)
    public configJson: JsonAsset = null;
    public jsonData: object
    onLoad() {
        this.moduleName = "Actor";
        this.addModule(this);
        this.jsonData = this.configJson.json;
    }

    ReceiveMessage(message: Message) {

    }


    /**
     * 随机获取角色
     * @param Parent 
     * @returns 
     */
    async getRandomRole(Parent: Node): Promise<RoleBase> {
        let random = Math.floor(Math.random() * this.jsonData["Roles"].length);
        let roleName = this.jsonData["Roles"][random];
        return this.getRole(Parent, roleName);
    }
    /**
     * 随机获取怪物
     * @param Parent 
     * @returns 
     */
    async getRandomMonster(Parent: Node): Promise<MonsterBase> {
        let random = Math.floor(Math.random() * this.jsonData["Monsters"].length);
        let roleName = this.jsonData["Monsters"][random];
        return this.getMonster(Parent, roleName);
    }
    /**
     * 获取角色
     * @param Parent 要设置的父节点
     * @param roleName 角色名
     * @returns Promise<RoleBase>
     */
    async getRole(Parent: Node, roleName: string): Promise<RoleBase> {
        return this.getActor("Role", Parent, roleName) as Promise<RoleBase>;
    }
    /**
     * 获取怪物
     * @param Parent 要设置的父节点
     * @param roleName 怪物名
     * @returns Promise<RoleBase>
     */
    async getMonster(Parent: Node, roleName: string): Promise<MonsterBase> {
        return this.getActor("Monster", Parent, roleName) as Promise<MonsterBase>;
    }

    //获取所有类型的actor
    getActor(actorType: string, Parent: Node, actorName: string): Promise<ActorBase> {
        return new Promise<ActorBase>((resolve, reject) => {
            let numName:string;
            if (actorType === "Role") {
                numName = actorName + "/" + actorName;
            } else {
                numName = actorName;
            }

            resources.load("Actor/" + actorType + "/" + numName, Prefab, (err, data) => {
                if (err) {
                    reject(actorType + "不存在");
                }
                const prefabNode: Node = instantiate(data);
                prefabNode.setParent(Parent);
                if (prefabNode) {
                    resolve(prefabNode.getComponent(ActorBase));
                }
            });
        });
    }

    onDestroy() {
        this.closeModule(this.moduleName);
    }

}
